
/**
  ******************************************************************************
  * Copyright 2021 The Microbee Authors. All Rights Reserved.
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  * http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * 
  * @file       sensor_gps_nmea.h
  * @author     baiyang
  * @date       2023-2-14
  ******************************************************************************
  */

#pragma once

#ifdef __cplusplus
extern "C"{
#endif

/*----------------------------------include-----------------------------------*/
#include <stdint.h>
#include <stdbool.h>

#include "sensor_gps.h"
#include "sensor_gps_backend.h"
/*-----------------------------------macro------------------------------------*/
#if MB_GPS_NMEA_ENABLED

#if MB_GPS_NMEA_UNICORE_ENABLED && !defined(NMEA_UNICORE_SETUP)
// we don't know what port the GPS may be using, so configure all 3. We need to get it sending
// one message to allow the NMEA detector to run
#define NMEA_UNICORE_SETUP "CONFIG COM1 230400 8 n 1\r\nCONFIG COM2 230400 8 n 1\r\nCONFIG COM3 230400 8 n 1\r\nGPGGA 0.2\r\n"
#endif

// output message: GGA,RMC,VTG
// output frequency: 10Hz
// baudrate: 115200
#define CASIC_SET_BINARY_115200 "$PCAS03,1,0,0,0,1,1,0,0*03\r\n$PCAS02,100*1E\r\n$PCAS04,3*1A\r\n$PCAS01,5*19\r\n$PCAS00*01\r\n"
/*----------------------------------typedef-----------------------------------*/
/// Coding for the GPS sentences that the parser handles
enum _sentence_types {      //there are some more than 10 fields in some sentences , thus we have to increase these value.
    _GPS_SENTENCE_RMC = 32,
    _GPS_SENTENCE_GGA = 64,
    _GPS_SENTENCE_VTG = 96,
    _GPS_SENTENCE_HDT = 128,
    _GPS_SENTENCE_PHD = 138, // extension for AllyStar GPS modules
    _GPS_SENTENCE_THS = 160, // True heading with quality indicator, available on Trimble MB-Two
    _GPS_SENTENCE_KSXT = 170, // extension for Unicore, 21 fields
    _GPS_SENTENCE_AGRICA = 193, // extension for Unicore, 65 fields
    _GPS_SENTENCE_VERSIONA = 270, // extension for Unicore, version, 10 fields
    _GPS_SENTENCE_UNIHEADINGA = 290, // extension for Unicore, uniheadinga, 20 fields
    _GPS_SENTENCE_OTHER = 0
};

typedef struct sensor_gps_nmea* sensor_gps_nmea_t;
struct sensor_gps_nmea {
    struct sensor_gps_backend backend;

    uint8_t _parity;                                                    ///< NMEA message checksum accumulator
    uint32_t _crc32;                                            ///< CRC for unicore messages
    bool _is_checksum_term;                                     ///< current term is the checksum
    char _term[30];                                                     ///< buffer for the current term within the current sentence
    uint16_t _sentence_type;                                     ///< the sentence type currently being processed
    bool _is_unicore;                                           ///< true if in a unicore '#' sentence
    uint16_t _term_number;                                       ///< term index within the current sentence
    uint8_t _term_offset;                                       ///< character offset with the term being received
    uint16_t _sentence_length;
    bool _sentence_done;                                        ///< set when a sentence has been fully decoded

    // The result of parsing terms within a message is stored temporarily until
    // the message is completely processed and the checksum validated.
    // This avoids the need to buffer the entire message.
    int32_t _new_time;                                                  ///< time parsed from a term
    int32_t _new_date;                                                  ///< date parsed from a term
    int32_t _new_latitude;                                      ///< latitude parsed from a term
    int32_t _new_longitude;                                     ///< longitude parsed from a term
    int32_t _new_altitude;                                      ///< altitude parsed from a term
    int32_t _new_speed;                                                 ///< speed parsed from a term
    int32_t _new_course;                                        ///< course parsed from a term
    float   _new_gps_yaw;                                        ///< yaw parsed from a term
    uint16_t _new_hdop;                                                 ///< HDOP parsed from a term
    uint8_t _new_satellite_count;                       ///< satellite count parsed from a term
    uint8_t _new_quality_indicator;                                     ///< GPS quality indicator parsed from a term

    uint32_t _last_RMC_ms;
    uint32_t _last_GGA_ms;
    uint32_t _last_VTG_ms;
    uint32_t _last_yaw_ms;
    uint32_t _last_vvelocity_ms;
    uint32_t _last_vaccuracy_ms;
    uint32_t _last_3D_velocity_ms;
    uint32_t _last_KSXT_pos_ms;
    uint32_t _last_AGRICA_ms;
    uint32_t _last_fix_ms;

    /*
      the $PHD message is an extension from AllyStar that gives
      vertical velocity and more accuracy estimates. It is designed as
      a mapping from ublox UBX protocol messages to NMEA. So class 1,
      message 12 is a mapping to NMEA of the NAV-VELNED UBX message
      and contains the same fields. Class 1 message 26 is called
      "NAV-PVERR", but does not correspond to a UBX message

      example:
        $PHD,01,12,TIIITTITT,,245808000,0,0,0,0,0,10260304,0,0*27
        $PHD,01,26,TTTTTTT,,245808000,877,864,1451,11,11,17*17
     */
    struct {
        uint8_t msg_class;
        uint8_t msg_id;
        uint32_t itow;
        int32_t fields[8];
    } _phd;

    /*
      The KSXT message is an extension from Unicore that gives 3D velocity and yaw
      example: $KSXT,20211016083433.00,116.31296102,39.95817066,49.4911,223.57,-11.32,330.19,0.024,,1,3,28,27,,,,-0.012,0.021,0.020,,*2D
     */
    struct {
        double fields[21];
    } _ksxt;

#if MB_GPS_NMEA_UNICORE_ENABLED
    /*
      unicore AGRICA message parsing
     */
    struct {
        uint32_t start_byte;
        uint8_t rtk_status;
        uint8_t heading_status;
        Vector3f_t vel_NED;
        Vector3f_t vel_stddev;
        double lat, lng;
        float alt;
        uint32_t itow;
        float undulation;
        Vector3f_t pos_stddev;
    } _agrica;

    // unicore VERSIONA parsing
    struct {
        char type[10];
        char version[20];
        char build_date[13];
    } _versiona;
    bool _have_unicore_versiona;

#if GPS_MOVING_BASELINE
    // unicore UNIHEADINGA parsing
    struct {
        float baseline_length;
        float heading;
        float pitch;
        float heading_sd;
    } _uniheadinga;
#endif
#endif // AP_GPS_NMEA_UNICORE_ENABLED
    bool _expect_agrica;

    // last time we sent type specific config strings
    uint32_t last_config_ms;
};

/*----------------------------------variable----------------------------------*/

/*-------------------------------------os-------------------------------------*/

/*----------------------------------function----------------------------------*/
void sensor_gps_nmea_ctor(sensor_gps_nmea_t gps_nmea, struct GPS_State *_state, rt_device_t _port);
sensor_gps_backend_t sensor_gps_nmea_probe(struct GPS_State *_state, rt_device_t _port);
bool sensor_gps_nmea_detect(struct NMEA_detect_state *state, uint8_t data);
/*------------------------------------test------------------------------------*/
#endif // MB_GPS_NMEA_ENABLED

#ifdef __cplusplus
}
#endif



